#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Copyright (c) 2025 粤港澳大湾区（广东）国创中心

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <https://www.gnu.org/licenses/>.

File: PythonFeatureTreeDlg.py
Desc: A dialog to display and manage a tree of Python features.
Author: xumanjia
Date: 2025-08-01
"""
import sys
from PyQt5.QtWidgets import QApplication, QDialog, QTreeWidget, QVBoxLayout, QTreeWidgetItem,QSizePolicy,QPushButton
from PyQt5.QtCore import Qt
from Pub.configLoad import global_scope
class PythonFeatureTreeDlg(QDialog):
    def __init__(self):
        super().__init__()
        global global_scope
        self.doc = global_scope["doc"]
        self.NCTI = global_scope["NCTI"]
        self.treeWidget = QTreeWidget(self)
        mainLayout = QVBoxLayout(self)
        mainLayout.addWidget(self.treeWidget)
        self.treeWidget.setColumnCount(1)
        self.treeWidget.setHeaderHidden(True)
        self.treeWidget.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.treeWidget.itemClicked.connect(self.on_tree_item_clicked)
        self.btnRemove = QPushButton("移除特征")
        mainLayout.addWidget(self.btnRemove, 0, Qt.AlignmentFlag.AlignCenter)
        self.btnRemove.clicked.connect(self.on_btn_remove_clicked)
        self.setLayout(mainLayout)
        self.title = "特征列表"
        self.setWindowTitle(self.title)
        #self.setGeometry(100, 100, 400, 200)
        self.setWindowFlags(self.windowFlags() & ~Qt.WindowContextHelpButtonHint)

    def init(self, *argsTuple):
        print(argsTuple)
        size = len(argsTuple)
        if size == 2:
            featureType = argsTuple[0]
            argsData = argsTuple[1]
            if not isinstance(argsData,dict):
                print("FeatureTreeDlg init failed!")
                return
            for key, value in argsData.items():
                bodyName = key
                firstItem = QTreeWidgetItem(self.treeWidget)
                firstItem.setCheckState(0,0)
                firstItem.setText(0, bodyName)
                if isinstance(value,list):
                    for levs in value:
                        secodeItem = QTreeWidgetItem(firstItem)
                        secodeItem.setCheckState(0,0)
                        secondItemText = ''
                        if isinstance(levs,list):
                            for cell in levs:
                                if secondItemText != '':
                                    secondItemText += ','
                                secondItemText += str(cell)
                            secondItemText = '[' + secondItemText + ']'
                        elif isinstance(levs,int):
                            secondItemText = f'[{str(levs)}]'
                        secodeItem.setText(0, secondItemText)
                        secodeItem.setData(0, Qt.UserRole, levs)
                firstItem.setData(0, Qt.UserRole, value)
        self.treeWidget.expandAll()

    def on_tree_item_clicked(self, item, column):
        data = item.data(column, Qt.UserRole)
        cells = []
        if item.parent() == None:
            bodyName = item.text(column)
            if isinstance(data,list):
                for value in data:
                    if isinstance(value,list):
                        cells.extend(value)
                    else:
                        cells.append(value)
        else:
            bodyName = item.parent().text(column)
            cells = data
        self.zoomCellIDs(bodyName,cells)
    
    def on_btn_remove_clicked(self):
        bodyNames = []
        cellss = []
        items = []
        for i in range(self.treeWidget.topLevelItemCount()):
            bodyCells = []
            item = self.treeWidget.topLevelItem(i)
            if(item.checkState(0) == Qt.CheckState.Checked):
                bodyNames.append(item.text(0))
                data = item.data(0, Qt.UserRole)
                for value in data:
                    if isinstance(value,list):
                        bodyCells.extend(value)
                    else:
                        bodyCells.append(value)
                items.append(item)
            else:
                hasChecked = 0
                for childIdx in range(item.childCount()):
                    childItem = item.child(childIdx)
                    if(childItem.checkState(0) == Qt.CheckState.Checked):
                        hasChecked = 1
                        data = childItem.data(0, Qt.UserRole)
                        if isinstance(data,list):
                            bodyCells.extend(data)
                        else:
                            bodyCells.append(data)
                        items.append(childItem)
                if len(items) == item.childCount():
                    items.clear()
                    items.append(item)
                if hasChecked == 1:
                    bodyNames.append(item.text(0))
            if len(bodyCells) > 0:
                cellss.append(bodyCells)

        if len(bodyNames) == len(cellss):
            for idx in range(len(bodyNames)):
                self.doc.RunCommand("cmd_ncti_remove_features",bodyNames[idx],cellss[idx])

        self.removeTreeItem(items)
        
    
    def zoomCellIDs(self, modelName, cellIDs):
        names = []
        cells = []
        sel = self.NCTI.SelectionManager(self.doc)
        sel.ClearSelected()
        if isinstance(cellIDs,list):
            for i in cellIDs:
                names.append(modelName)
                cells.append(i)
        else:
            names.append(modelName)
            cells.append(cellIDs)

        sel.ObjectNames = names
        sel.CellIDs = cells
        sel.SetSelected()
        view = self.NCTI.View(self.doc.ID)
        view.Zoom(sel.ObjectNames,sel.CellIDs)
        self.doc.Update()

    def removeTreeItem(self,items):
        for item in items:
            self.delete_item_and_children(item)

    def delete_item_and_children(self,parent_item):
        # 删除所有子项
        while parent_item.childCount() > 0:
            child_item = parent_item.child(0)
            self.delete_item_and_children(child_item)  # 递归删除子项
            parent_item.removeChild(child_item)   # 从父项中移除子项

        # 删除当前项
        parent_item.parent().removeChild(parent_item) if parent_item.parent() else None

def InputFeatureTreeDlg(*arg):
    window = PythonFeatureTreeDlg()
    window.init(*arg)
    window.show()
    if window.exec_() == QDialog.Accepted:
        val = tuple(window)
        print(val)
        return val

